﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Documents;
using Pavilion.DesignerTool.ViewTools;

namespace Pavilion.DesignerTool.NodeDesignerTool
{
    public class ConnectionDrawer
    {
        private ListBox ListBox { get; set; }
        private bool IsSecondTime { get; set; }
       
        public ConnectionDrawer(ListBox listBox)
        {
            ListBox = listBox;
            IsSecondTime = false;
        }

        public void DrawConnections(IEnumerable<NodeBase> nodes)
        {            
            List<Connection> connectionsForAllListBoxItems = new List<Connection>();

            foreach (var node in nodes)
            {
                Canvas parentCanvas = GetCanvasContainingNode(node);

                List<Connection> connectionsFromListBoxItem = BuildConnectionsForNode(node, parentCanvas);

                foreach (var connection in connectionsFromListBoxItem)
                    ;//AdornerLayer.GetAdornerLayer(parentCanvas).Add(connection);
            }
        }

        private Canvas GetCanvasContainingNode(NodeBase node)
        {
            ListBoxItem container = this.ListBox.ItemContainerGenerator.ContainerFromItem(node) as ListBoxItem;
            return PavilionVisualTreeHelper.GetAncestor(container, typeof(CustomCanvas)) as Canvas;
        }

        private List<Connection> BuildConnectionsForNode(NodeBase node, UIElement adornedElement)
        {   
            List<Connection> connections = new List<Connection>();

            foreach (var link in node.LinkCollection)
            {
                Connection newConnection = CreateConnectionFromLink(adornedElement, link);
                connections.Add(newConnection);
            }

            return connections;           
        }
 
        private Connection CreateConnectionFromLink(UIElement adornedElement, Link link)
        {
            var startContainer = ListBox.ItemContainerGenerator.ContainerFromItem(link.StartingNode) as ListBoxItem;
            var endContainer = ListBox.ItemContainerGenerator.ContainerFromItem(link.EndingNode) as ListBoxItem;

            var startAnchor = GetAnchor(startContainer);
            var endAnchor = GetAnchor(endContainer);

            //Connection newConnection = new Connection(startAnchor, endAnchor);
            //newConnection.Link = link;

            return null;
        }

        public static Anchor GetAnchor(ListBoxItem listBoxItem)
        {
            //pick a random anchor
            Random random = new Random();
            int anchorNumber = random.Next(4);
            UIElementCollection collectionOfAnchors = null;

            VisualTreeWalker walker = new VisualTreeWalker();
            walker.VisualVisited += (sender, e) => 
            {
                if (e.VisitedVisual is Grid)
                {
                    Grid grid = e.VisitedVisual as Grid;
                    if (grid.Name.Equals("anchorGrid"))
                        collectionOfAnchors = grid.Children;
                }
            };
            walker.Walk(listBoxItem);

            return ChooseAnchor(collectionOfAnchors, anchorNumber);
        }

        private static Anchor ChooseAnchor(UIElementCollection collectionOfAnchors, int choice)
        {
            System.Windows.HorizontalAlignment desiredHorizontalAlignment;
            System.Windows.VerticalAlignment desiredVerticalAlignment;

            GetCorrectAlignmentsForAnchor(choice, out desiredHorizontalAlignment, out desiredVerticalAlignment);

            foreach (var uiElement in collectionOfAnchors)
            {
                Anchor anchor = uiElement as Anchor;
                if (anchor != null && anchor.VerticalAlignment == desiredVerticalAlignment && anchor.HorizontalAlignment == desiredHorizontalAlignment)
                    return anchor;
            }

            return null;
        }

        private static void GetCorrectAlignmentsForAnchor(int choice, out HorizontalAlignment desiredHorizontalAlignment, out VerticalAlignment desiredVerticalAlignment)
        {
            if (choice == 0)
            {
                desiredHorizontalAlignment = HorizontalAlignment.Left;
                desiredVerticalAlignment = VerticalAlignment.Center;
            }
            else if (choice == 1)
            {
                desiredHorizontalAlignment = HorizontalAlignment.Center;
                desiredVerticalAlignment = VerticalAlignment.Top;
            }
            else if (choice == 2)
            {
                desiredHorizontalAlignment = HorizontalAlignment.Right;
                desiredVerticalAlignment = VerticalAlignment.Center;
            }
            else if (choice == 3)
            {
                desiredHorizontalAlignment = HorizontalAlignment.Center;
                desiredVerticalAlignment = VerticalAlignment.Bottom;
            }
            else throw new ArgumentOutOfRangeException(string.Format("int choice needs to be between 0 and 3. You passed {0}", choice));
        }      
    }
}
